<template>
  <a-modal
    v-model:visible="visible"
    @close="close"
    title="绑定微信"
    class="modal-dialog-wrapper"
    :mask-closable="false"
    width="400px"
    popup-container="body"
  >
    <div class="main">
      <div id="wx_qrcode_container"></div>
    </div>
    <template #footer>
      <div></div>
    </template>
  </a-modal>
</template>

<script setup>
  import { watch, ref } from 'vue'
  import { getCreateCodeUrlParam, getWxQrAfterLoginAfterResult } from '@/api/user'
  import { useRoute, useRouter } from 'vue-router'
  import { Message, Modal } from '@arco-design/web-vue'

  const emits = defineEmits(['ok'])

  const route = useRoute()
  const router = useRouter()
  const visible = ref(false)
  const open = () => {
    visible.value = true
    initWxQrcode()
  }
  // 关闭
  const close = () => {
    visible.value = false
  }

  // 获取微信二维码
  const initWxQrcode = () => {
    const env = import.meta.env.VITE_ENV
    getCreateCodeUrlParam({ redirectUrl: `https://image.qichengcx.com/html/login_jump.html?env=${env}&path=home` }).then((res) => {
      const data = res.result
      new WxLogin({
        id: 'wx_qrcode_container',
        appid: data.appid,
        scope: data.scope,
        redirect_uri: data.redirectUrl,
        state: data.state,
        stylelite: 1, // 新样式无效
        href: 'data:text/css;base64,QGNoYXJzZXQgInV0Zi04IjsKLmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDI4MHB4OyBib3JkZXItcmFkaXVzOiAxNnB4O2JvcmRlcjogMXB4IHNvbGlkICNDNUM2Q0Q7fQouaW1wb3dlckJveCAudGl0bGUge2Rpc3BsYXk6IG5vbmU7fQouaW1wb3dlckJveCAuaW5mbyB7d2lkdGg6IDIzOHB4O30KLmltcG93ZXJCb3ggLnN0YXR1cyB7dGV4dC1hbGlnbjogY2VudGVyO3BhZGRpbmc6IDB9Cg==',
      })
    })
  }

  const getWxLoginCallback = () => {
    const data = route.query
    if (!data.code || data.source != 'login_jump') return
    // 已登录绑定微信
    getWxQrAfterLoginAfterResult(data).then((res) => {
      if (res.code == 200) {
        const { status, statusCode, message } = res.result
        // 清空路由参数
        router.replace({ path: '/', query: {} })
        // 打开用户信息弹框
        emits('ok')
        // status：true 已绑定 false 未绑定
        setTimeout(() => {
          if (status) {
            if (statusCode == 30) {
              Modal.error({
                title: '绑定失败',
                content: '该微信已经绑定了其他登录名，请先解绑',
              })
              return
            }
            Modal.success({
              simple: true,
              title: '绑定成功',
            })
            return
          }
          Message.error(message)
        }, 500)
      }
    })
  }

  watch(
    () => route.fullPath,
    () => {
      // 获取微信二维码登录结果
      getWxLoginCallback()
    },
    { immediate: true }
  )

  defineExpose({ open })
</script>

<style lang="less" scoped>
  .main {
    display: flex;
    justify-content: center;
    margin-top: 9px;
  }

  :deep(.arco-modal-footer) {
    display: none !important;
  }
</style>
